﻿using System;
using System.IO;

namespace Comdiv.QWeb.Remoting {
	public class LocalConnection : ConnectionBase {
		private readonly QWebServiceRegistry registry;

		public LocalConnection(QWebServiceRegistry qwebregistry) {
			registry = qwebregistry;
		}

		protected override QWebResult internalCall(QWebQuery query) {
			var ctx = new QWebContext();
			var sw = new StringWriter();
			ctx.Output = sw;
			query.Setup("http://localhost/", ctx);
			var handler = new QWebHandler(registry);
			var result = new QWebResult();
			try {
				handler.ProcessRequest(ctx);

				result.ActionResult = ctx.ActionResult;
				result.Content = sw.ToString();
				result.ETag = ctx.Etag;
				result.LastModified = ctx.LastModified;
				result.Status = ctx.StatusCode;
				result.Error = ctx.Error;
			}
			catch (Exception e) {
				result.Error = e;
			}
			return result;
		}
	}
}